package com.derbysoft.synxisadapter.commons.servlet;

import com.derbysoft.synxisadapter.dswitch2.service.MonitorService;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class MonitorServlet extends HttpServlet {
    private WebApplicationContext webApplicationContext;
    private MonitorService monitorService;

    @Override
    public void init(ServletConfig servletConfig) throws ServletException {
        super.init(servletConfig);
        webApplicationContext = WebApplicationContextUtils.getWebApplicationContext(servletConfig.getServletContext());
        String value = servletConfig.getInitParameter("monitorService");
        monitorService = (MonitorService) getBean(value);
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        monitorService.doTest();
        response.getOutputStream().println("OK");
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }

    private Object getBean(String beanName) {
        return webApplicationContext.getBean(beanName);
    }

}
